package handler

import (
	"net/http"
	"time"

	"github.com/gin-gonic/gin"
	"goserver/internal/service"
)

type StatsHandler struct {
	statsService *service.StatsService
}

func NewStatsHandler(statsService *service.StatsService) *StatsHandler {
	return &StatsHandler{
		statsService: statsService,
	}
}

// GetMessageStats 获取消息统计
func (h *StatsHandler) GetMessageStats(c *gin.Context) {
	// 解析时间范围
	startDate := c.Query("start_date")
	endDate := c.Query("end_date")

	start, err := time.Parse("2006-01-02", startDate)
	if err != nil {
		start = time.Now().AddDate(0, 0, -7) // 默认最近7天
	}

	end, err := time.Parse("2006-01-02", endDate)
	if err != nil {
		end = time.Now()
	}

	// 获取统计数据
	stats, err := h.statsService.GetMessageStats(c.Request.Context(), start, end)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code":    500,
			"message": "获取统计数据失败",
			"error":   err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code":    200,
		"message": "获取���功",
		"data":    stats,
	})
}

// GetDeviceStats 获取设备统计
func (h *StatsHandler) GetDeviceStats(c *gin.Context) {
	// 解析时间范围
	startDate := c.Query("start_date")
	endDate := c.Query("end_date")

	start, err := time.Parse("2006-01-02", startDate)
	if err != nil {
		start = time.Now().AddDate(0, 0, -7) // 默认最近7天
	}

	end, err := time.Parse("2006-01-02", endDate)
	if err != nil {
		end = time.Now()
	}

	// 获取统计数据
	stats, err := h.statsService.GetDeviceStats(c.Request.Context(), start, end)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code":    500,
			"message": "获取统计数据失败",
			"error":   err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code":    200,
		"message": "获取成功",
		"data":    stats,
	})
}

// GetRobotCodeStats 获取机器码统计
func (h *StatsHandler) GetRobotCodeStats(c *gin.Context) {
	// 获取统计数据
	stats, err := h.statsService.GetRobotCodeStats(c.Request.Context())
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code":    500,
			"message": "获取统计数据失败",
			"error":   err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code":    200,
		"message": "获取成功",
		"data":    stats,
	})
} 